package models

import (
	"encoding/json"
	"time"
)

// DynamicRecord 动态记录结构
type DynamicRecord map[string]interface{}

// APIResponse 通用API响应结构
type APIResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
	Total   int64       `json:"total,omitempty"`
}

// PaginationRequest 分页请求
type PaginationRequest struct {
	Page     int    `json:"page" form:"page"`
	PageSize int    `json:"page_size" form:"page_size"`
	OrderBy  string `json:"order_by" form:"order_by"`
	Order    string `json:"order" form:"order"` // asc, desc
	Search   string `json:"search" form:"search"`
}

// PaginationResponse 分页响应
type PaginationResponse struct {
	Page     int           `json:"page"`
	PageSize int           `json:"page_size"`
	Total    int64         `json:"total"`
	Data     []interface{} `json:"data"`
}

// TableMapping 表映射配置
type TableMapping struct {
	DisplayName string                  `yaml:"display_name" json:"display_name"`
	Description string                  `yaml:"description" json:"description"`
	Icon        string                  `yaml:"icon" json:"icon"`
	Fields      map[string]FieldMapping `yaml:"fields" json:"fields"`
	Operations  OperationMapping        `yaml:"operations" json:"operations"`
	Permissions PermissionMapping       `yaml:"permissions" json:"permissions"`
}

// FieldMapping 字段映射配置
type FieldMapping struct {
	DisplayName string   `yaml:"display_name" json:"display_name"`
	Type        string   `yaml:"type" json:"type"`
	Required    bool     `yaml:"required" json:"required"`
	Readonly    bool     `yaml:"readonly" json:"readonly"`
	Hidden      bool     `yaml:"hidden" json:"hidden"`
	Validation  string   `yaml:"validation" json:"validation"`
	Options     []Option `yaml:"options" json:"options"`
}

// Option 选项配置
type Option struct {
	Label string `yaml:"label" json:"label"`
	Value string `yaml:"value" json:"value"`
}

// OperationMapping 操作映射配置
type OperationMapping struct {
	Create bool `yaml:"create" json:"create"`
	Read   bool `yaml:"read" json:"read"`
	Update bool `yaml:"update" json:"update"`
	Delete bool `yaml:"delete" json:"delete"`
}

// PermissionMapping 权限映射配置
type PermissionMapping struct {
	Roles []string `yaml:"roles" json:"roles"`
}

// GlobalConfig 全局配置
type GlobalConfig struct {
	Pagination PaginationConfig `yaml:"pagination" json:"pagination"`
	DateFormat string           `yaml:"date_format" json:"date_format"`
	Timezone   string           `yaml:"timezone" json:"timezone"`
}

// PaginationConfig 分页配置
type PaginationConfig struct {
	DefaultPageSize int `yaml:"default_page_size" json:"default_page_size"`
	MaxPageSize     int `yaml:"max_page_size" json:"max_page_size"`
}

// MappingConfig 映射配置文件结构
type MappingConfig struct {
	Mappings map[string]TableMapping `yaml:"mappings" json:"mappings"`
	Global   GlobalConfig            `yaml:"global" json:"global"`
}

// NewSuccessResponse 创建成功响应
func NewSuccessResponse(data interface{}) *APIResponse {
	return &APIResponse{
		Code:    200,
		Message: "success",
		Data:    data,
	}
}

// NewErrorResponse 创建错误响应
func NewErrorResponse(code int, message string) *APIResponse {
	return &APIResponse{
		Code:    code,
		Message: message,
	}
}

// NewPaginationResponse 创建分页响应
func NewPaginationResponse(page, pageSize int, total int64, data []interface{}) *APIResponse {
	return &APIResponse{
		Code:    200,
		Message: "success",
		Data: PaginationResponse{
			Page:     page,
			PageSize: pageSize,
			Total:    total,
			Data:     data,
		},
	}
}

// ToJSON 转换为JSON字符串
func (r *DynamicRecord) ToJSON() (string, error) {
	data, err := json.Marshal(r)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

// FromJSON 从JSON字符串解析
func (r *DynamicRecord) FromJSON(jsonStr string) error {
	return json.Unmarshal([]byte(jsonStr), r)
}

// GetString 获取字符串值
func (r DynamicRecord) GetString(key string) string {
	if val, ok := r[key]; ok {
		if str, ok := val.(string); ok {
			return str
		}
	}
	return ""
}

// GetInt 获取整数值
func (r DynamicRecord) GetInt(key string) int {
	if val, ok := r[key]; ok {
		switch v := val.(type) {
		case int:
			return v
		case int64:
			return int(v)
		case float64:
			return int(v)
		}
	}
	return 0
}

// GetFloat 获取浮点数值
func (r DynamicRecord) GetFloat(key string) float64 {
	if val, ok := r[key]; ok {
		switch v := val.(type) {
		case float64:
			return v
		case float32:
			return float64(v)
		case int:
			return float64(v)
		case int64:
			return float64(v)
		}
	}
	return 0
}

// GetBool 获取布尔值
func (r DynamicRecord) GetBool(key string) bool {
	if val, ok := r[key]; ok {
		if b, ok := val.(bool); ok {
			return b
		}
	}
	return false
}

// GetTime 获取时间值
func (r DynamicRecord) GetTime(key string) *time.Time {
	if val, ok := r[key]; ok {
		switch v := val.(type) {
		case time.Time:
			return &v
		case string:
			if t, err := time.Parse(time.RFC3339, v); err == nil {
				return &t
			}
		}
	}
	return nil
}
